<!-- 算法配置相关页面 -->
<template>
    <div class="container">
        <div class="header">
            <el-select
            v-model="value"
            placeholder="场景选择"
            size="large"
            style="width: 240px"
        >
            <el-option
            v-for="item in formattedOptionsForFilter"
            :key="item.key"
            :label="item.label"
            :value="item.value"
            />
        </el-select>
        <el-button type="primary" style="width: 10rem;height: 2.7rem;margin-left: 2rem;" @click="addAlgorithm()">新建算法演示</el-button>  
        <!-- 点击按钮触发的弹窗 -->
        <el-dialog
             v-model="dialogVisibleAdd"
             title="新建演示算法"
             width="500" 
        >
        <div style="width: 100%" v-loading="addNewLoadding">
        <div style="width: 100%;display: flex;justify-content: space-evenly;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span>  算法名称：</div>  <el-input v-model="AlgorName" style="width: 70%;height: 2rem;" />
        </div>
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 所属场景：</div>      
            <el-select
            v-model="valueAdd"
            placeholder="所属场景"
            style="width: 70%"
        >
            <el-option
            v-for="item in formattedOptions"
            :key="item.key"
            :label="item.label"
            :value="item.value"
            />
        </el-select>
        </div>
        <!-- 上传图片“封面”只能上传一张 -->
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 算法封面</div>   
            <div style="width: 70%;">
                <el-upload
                v-model:file-list="fileListCoverImg"
                :limit="1"
                :auto-upload="false"
                list-type="picture-card"
                :on-preview="handlePictureCardPreviewOne"
                :on-remove="handleRemoveOne"
                multiple 
                accept="image/*" 
            >
        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogCoverImg">
        <img style="width: 100%;" :src="dialogCoverImageUrl" alt="Preview Image" />
      </el-dialog>
            </div>   
        </div>

      <!-- 上传示例图片 -->
      <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
      <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 算法示例图</div>   
      <div style="width: 70%;">
      <el-upload
        v-model:file-list="fileListSampleImg"
        :limit="1"
        :auto-upload="false"
        list-type="picture-card"
        :on-preview="handlePictureCardPreviewSix"
        :on-remove="handleRemoveSix"
        multiple 
        accept="image/*" 
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogSampleImg">
        <img style="width: 100%;height: 100%;" :src="dialogSampleImageUrl" alt="Preview Image" />
      </el-dialog>
    </div>
    </div>
      <!-- 算法描述 -->
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 算法描述：</div>  <el-input v-model="AlgorDescription" type="textarea" style="width: 70%;" />
        </div>
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> api地址:</div>  <el-input v-model="ApiLocation" style="width: 70%;height: 2rem;"  />
        </div>
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 是否调用大模型</div>   
            <el-switch
              style="width: 70%;height: 2rem;"
              v-model="modelStatusBoo"
              size="large"
              active-text="调用大模型"
              inactive-text="不调用大模型"
            />
        </div>



      </div>
       
        <template #footer>
            <div class="dialog-footer">
            <el-button @click="dialogVisibleAdd = false">取消</el-button>
            <el-button type="primary" @click="upLoadMessage">
                确定
            </el-button>
            </div>
        </template>
        </el-dialog>
        </div>
        <div class="main">
          <el-table
  :data="tableDataPaging"
  border
  style="width: 100%; background-color: #fff;"
  :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 600 }"
  highlight-current-row
>
  <!-- 序号 -->
  <el-table-column label="序号" width="60">
    <template #default="scope">
      {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
    </template>
  </el-table-column>

  <!-- 算法名称 -->
  <el-table-column prop="algorithmName" label="算法名称" width="100" />

  <!-- 所属场景 -->
  <el-table-column prop="scenarioName" label="所属场景" width="100" />

  <!-- 算法封面 -->
  <el-table-column label="算法封面" width="130">
    <template #default="scope">
      <img
        :src="scope.row.coverUrl"
        alt="算法封面"
        style="width: 100%; height: 80px; object-fit: cover; border-radius: 6px; border: 1px solid #eee;"
      />
    </template>
  </el-table-column>

  <!-- 演示例图 -->
  <el-table-column label="演示例图" width="130">
    <template #default="scope">
      <img
        :src="scope.row.exampleUrl"
        alt="演示例图"
        style="width: 100%; height: 80px; object-fit: cover; border-radius: 6px; border: 1px solid #eee;"
      />
    </template>
  </el-table-column>

  <!-- 算法描述 -->
  <el-table-column prop="description" label="算法描述" width="160" />

  <!-- API 地址 -->
  <el-table-column prop="apiAddress" label="API 地址" width="120" />

  <!-- 演示状态 -->
  <el-table-column prop="status" label="演示状态" width="100">
    <template #default="scope">
      <el-switch
        v-model="scope.row.status"
        :active-value="'S'"
        :inactive-value="'F'"
        @change="handleStatusChange(scope.row)"
      />
    </template>
  </el-table-column>

  <!-- 配置 -->
  <el-table-column prop="imagesArray" label="配置" width="70">
    <template #default="scope">
                    <el-button link type="primary" size="small" @click="changeImage(scope.row)">
                      {{ scope.row.imagesArray}}
                    </el-button>
                    </template>
  </el-table-column>

  <!-- 提示词 -->
  <el-table-column prop="imagesArray" label="提示词" width="140">
    <template #default="scope">
      <el-input
        v-if="scope.row.modelStatus === 'S'"
        v-model="scope.row.cueWord"
        size="small"
        placeholder="请输入提示词"
        @blur="handleInputBlur(scope.row)"
        clearable
      />
      <span v-else>--</span>
    </template>
  </el-table-column>

  <!-- 操作 -->
  <el-table-column prop="apiAddress" label="操作" width="260">
    <template #default="scope">
      <div style="display: flex; flex-wrap: wrap; gap: 6px;">
        <el-button
          v-if="value"
          link
          type="primary"
          size="small"
          @click="moveToTop(scope.row)"
          style="color: lightsalmon;"
        >
          置顶
        </el-button>
        <el-button
          v-if="value"
          link
          type="primary"
          size="small"
          :icon="ArrowUp"
          @click="moveUp(scope.row)"
        />
        <el-button
          v-if="value"
          link
          type="primary"
          size="small"
          :icon="ArrowDown"
          @click="moveDown(scope.row)"
        />
        <el-button
          v-if="value"
          link
          type="primary"
          size="small"
          @click="moveToBottom(scope.row)"
          style="color: lightseagreen;"
        >
          沉底
        </el-button>
        <el-button
          link
          type="primary"
          size="small"
          @click="changeAlgorithm(scope.row)"
        >
          修改
        </el-button>
        <el-button
          link
          type="primary"
          size="small"
          style="color: red;"
          @click="deleteItem(scope.row)"
        >
          删除
        </el-button>
      </div>
    </template>
  </el-table-column>
</el-table>

        </div>
        <div>
        </div>
        <Pagination
            :total="totalItems || 0"
            :page-size="pageSize"
            v-model:currentPage="currentPage"
             />

             <!-- 修改按钮点击出现的弹窗 -->
             <el-dialog
             v-model="dialogVisibleChange"
             title="修改演示算法"
             width="500" 
        >
        <div v-loading="changeAlgorithmFlag" style="width: 100%;">

        <div style="width: 100%;display: flex;justify-content: space-evenly;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 算法名称：</div>  <el-input v-model="AlgorNameChange" style="width: 70%;height: 2rem;" />
        </div>
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 所属场景：</div>      
            <el-select
            v-model="valueChange"
            placeholder="所属场景"
            style="width: 70%"
        >
            <el-option
            v-for="item in formattedOptions"
            :key="item.key"
            :label="item.label"
            :value="item.value"
            />
        </el-select>
        </div>
        <!-- 上传图片“封面”只能上传一张 -->
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 算法封面</div>   
            <div style="width: 70%;">
                <el-upload
                v-model:file-list="fileListCoverImgChange"
                :limit="1"
                :auto-upload="false"
                list-type="picture-card"
                :on-preview="handlePictureCardPreviewOne"
                :on-remove="handleRemoveOne"
                multiple 
                accept="image/*" 
            >
        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogCoverImg">
        <img style="width: 100%;height: 100%;" :src="dialogCoverImageUrlChange" alt="Preview Image" />
      </el-dialog>
            </div>   
        </div>

      <!-- 上传示例图片 -->
      <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
      <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 算法示例图</div>   
      <div style="width: 70%;">
      <el-upload
        v-model:file-list="fileListSampleImgChange"
        :limit="1"
        :auto-upload="false"
        list-type="picture-card"
        :on-preview="handlePictureCardPreviewSix"
        :on-remove="handleRemoveSix"
        multiple 
        accept="image/*" 
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogSampleImg">
        <img style="width: 100%;height: 100%;" :src="dialogSampleImageUrlChange" alt="Preview Image" />
      </el-dialog>
    </div>
    </div>
      <!-- 算法描述 -->
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 算法描述：</div>  <el-input v-model="AlgorDescriptionChange" type="textarea" style="width: 70%;" />
        </div>
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;">  <span style="color: red;">*</span>  api地址:</div>  <el-input v-model="ApiLocationChange" style="width: 70%;height: 2rem;"  />
        </div>
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 是否调用大模型</div>   
            <el-switch
              style="width: 70%;height: 2rem;"
              v-model="modelStatusBoo"
              size="large"
              active-text="调用大模型"
              inactive-text="不调用大模型"
            />
        </div>

       </div>

        <template #footer>
            <div class="dialog-footer">
            <el-button @click="dialogVisibleChange = false">取消</el-button>
            <el-button type="primary" @click="upLoadMessage1">
                确定
            </el-button>
            </div>
        </template>
        </el-dialog>
        <!-- 点击配置按钮出现的弹窗 -->
        <el-dialog
             v-model="ConfigureImageDialogVisible"
             title="配置算法演示图片"
             width="500" 
        >
        <div style="width: 100%; " v-loading="loading">
        <!-- 上传演示图片（良好），最多上传6张 -->
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;">演示图片（良好）</div>   
            <div style="width: 70%;">
                <el-upload
                v-model:file-list="dispositionFileList"
                :limit="6"
                :auto-upload="false"
                list-type="picture-card"
                :on-preview="handlePictureCardPreviewOne"
                :on-remove="handleRemoveOne"
                multiple 
                accept="image/*" 
            >
             <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="dialogCoverImg">
              <img style="width: 100%;height: 100%;" :src="dispositionDialogImageUrl" alt="Preview Image" />
            </el-dialog>
            </div>   
        </div>

         <!-- 上传效果不好图片，最多上传1张 -->
         <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;">演示图片（较差）</div>   
            <div style="width: 70%;">
                <el-upload
                v-model:file-list="badImageFileOne"
                :limit="1"
                :auto-upload="false"
                list-type="picture-card"
                :on-preview="handlePictureCardPreviewOne"
                :on-remove="handleRemoveOne"
                multiple 
                accept="image/*" 
            >
             <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="dialogCoverImg">
              <img style="width: 100%;height: 100%;" :src="dispositionDialogImageUrl" alt="Preview Image" />
            </el-dialog>
            </div>   
        </div>
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 图片描述：</div>  <el-input v-model="badImageOneDescription" type="textarea" style="width: 70%;" />
        </div>

         <!-- 上传效果不好演示图片2，最多上传1张 -->
         <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;">演示图片（较差）</div>   
            <div style="width: 70%;">
                <el-upload
                v-model:file-list="badImageFileTwo"
                :limit="1"
                :auto-upload="false"
                list-type="picture-card"
                :on-preview="handlePictureCardPreviewOne"
                :on-remove="handleRemoveOne"
                multiple 
                accept="image/*" 
            >
             <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="dialogCoverImg">
              <img style="width: 100%;" :src="dispositionDialogImageUrl" alt="Preview Image" />
            </el-dialog>
            </div>   
        </div>

        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"> <span style="color: red;">*</span> 图片描述：</div>  <el-input v-model="badImageTwoDescription" type="textarea" style="width: 70%;" />
        </div>
      </div>
        <template #footer>
            <div class="dialog-footer">
            <el-button @click="ConfigureImageDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="upLoadMessage2">
                确定
            </el-button>
            </div>
        </template>
        </el-dialog>



    </div>
</template>

<script lang="ts" setup>
import { useAlgorStore } from '@/stores/algorothm';
import { ref ,computed,onMounted,watch} from 'vue';
import { Plus,ArrowUp,ArrowDown} from '@element-plus/icons-vue'
import {  type UploadProps,type UploadFile} from 'element-plus';
import { ElMessage ,ElMessageBox} from 'element-plus'
import request from '@/utils/request';
import Pagination from '../tool/Pagination.vue';

const modelStatusBoo = ref(true)
const tipWord = ref('prompt')
const AlgorName =ref()  //算法名称
const AlgorDescription =ref() //算法描述
const ApiLocation =ref()  //算法api
const AlgorNameChange =ref()  //算法名称
const AlgorDescriptionChange =ref() //算法描述
const ApiLocationChange=ref()  //算法api
const dialogCoverImg = ref(false)
const dialogSampleImg = ref(false)
const fileListCoverImg = ref<UploadFile[]>([]);//新建，封面
const fileListSampleImg = ref<UploadFile[]>([]);//新建，演示例图
const fileListCoverImgChange = ref<UploadFile[]>([]);//修改封面
const fileListSampleImgChange = ref<UploadFile[]>([]);//修改示例图片
const dispositionFileList = ref<UploadFile[]>([]);//这个是配置良好演示图片使用
const badImageFileOne  = ref<UploadFile[]>([]); //这个用于存储第一张较差的图片使用
const badImageFileTwo  = ref<UploadFile[]>([]); //这个用于存储第二张较差的图片使用
const badImageOneDescription = ref();//较差图片描述1
const badImageTwoDescription = ref();//较差图片描述2
const dispositionDialogImageUrl = ref('')//这个是配置演示图片使用
const dialogCoverImageUrl = ref('')
const dialogSampleImageUrl = ref('')
const dialogCoverImageUrlChange = ref('')
const dialogSampleImageUrlChange = ref('')
const value = ref()
const valueAdd = ref()
const valueChange = ref()
const dialogVisibleAdd = ref(false)
const dialogVisibleChange = ref(false)
const ConfigureImageDialogVisible = ref(false)
const algorStore = useAlgorStore()
const currentPage = ref(1); // 当前页
const pageSize = ref(3); // 每页条数
const algorithmByAlgorithmScenarioID = ref()




const addAlgorithm = () => {
    dialogVisibleAdd.value = true
}
const changeImage = (item: any) => {
  ConfigureImageDialogVisible.value = true;
  selectedId.value = item.id;

  // 确保 item.images 是一个数组
  const images = Array.isArray(item.images) ? item.images : [];

  // 获取 status 为 0 的图片
  const statusZeroImages = images.filter((image: any) => image.status == 0);
  dispositionFileList.value = statusZeroImages.map((image: any) => ({
    name: image.id.toString(), // 图片的唯一标识
    url: image.imageUrl,       // 图片 URL
    status: 'done',            // 设置图片状态为已上传
  }));

  // 获取 status 为 1 的图片
  const statusOneImages = images.filter((image: any) => image.status == 1);
  const badOne = <any>[];
    if(statusOneImages[0] == undefined) {
      badImageFileOne.value = []
      badImageOneDescription.value = ''
    }else {
      badOne.push(statusOneImages[0])
      badImageOneDescription.value =  statusOneImages[0]?.description || ''
      badImageFileOne.value = badOne.map((image: any) => ({
    name: image?.id.toString(), // 图片的唯一标识
    url: image?.imageUrl || '',       // 图片 URL
    status: 'done',            // 设置图片状态为已上传
  }));
    }
  const badTwo = <any>[];
    if(statusOneImages[0] == undefined) {
      badImageFileTwo.value = []
      badImageTwoDescription.value = ''
    }else {
      badTwo.push(statusOneImages[1])
      badImageTwoDescription.value =  statusOneImages[1]?.description || ''
      badImageFileTwo.value = badTwo.map((image: any) => ({
    name: image?.id.toString(), // 图片的唯一标识
    url: image?.imageUrl ||'',       // 图片 URL
    status: 'done',            // 设置图片状态为已上传
  }));
    }
};

const selectedId = ref()
const primaryAlgorithmName = ref()
const selectedStatus = ref()
const newOrderNumber = ref()
const changeAlgorithm = (item:any) => {
  ElMessageBox.confirm(

    `是否修改算法(${item.algorithmName})？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {         
       // 确保 coverUrl 和 exampleUrl 是有效的字符串
       const coverUrl = item.coverUrl && typeof item.coverUrl === 'string' ? item.coverUrl : '';
      const exampleUrl = item.exampleUrl && typeof item.exampleUrl === 'string' ? item.exampleUrl : '';

      // 设置封面图片列表，确保 status 是合法的 UploadStatus
      fileListCoverImgChange.value = [
        {
          name: "cover.png",    // 文件名
          url: coverUrl,        // 复现 coverUrl
          status: 'success', // 强制转换为合法的 UploadStatus
          uid: Date.now(),      // 使用当前时间戳作为 UID，确保唯一性
        }
      ];

      // 设置示例图片列表，确保 status 是合法的 UploadStatus
      fileListSampleImgChange.value = [
        {
          name: "example.jpg",  // 文件名
          url: exampleUrl,      // 复现 exampleUrl
          status: 'success',    // 强制转换为合法的 UploadStatus
          uid: Date.now(),      // 使用当前时间戳作为 UID，确保唯一性
        }
      ];
      valueChange.value = item.scenarioID
      newOrderNumber.value = item.orderNumber
      primaryAlgorithmName.value = item.algorithmName
      dialogVisibleChange.value = true
      AlgorNameChange.value = item.algorithmName
      ApiLocationChange.value = item.apiAddress
      AlgorDescriptionChange.value = item.description
      selectedId.value = item.id
      selectedStatus.value = item.status
      modelStatusBoo.value = item.modelStatus == 'S'? true : false
    })
    .catch(() => {
    })

}

//  上传图片等相关函数

  // 删除逻辑
  const handleRemoveOne: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
}
// 预览逻辑
const handlePictureCardPreviewOne: UploadProps['onPreview'] = (uploadFile) => {
  dispositionDialogImageUrl.value = uploadFile.url!
  dialogCoverImg.value = true
}
  // 删除逻辑
  const handleRemoveSix: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
}
// 预览逻辑
const handlePictureCardPreviewSix: UploadProps['onPreview'] = (uploadFile) => {
  dialogSampleImageUrl.value = uploadFile.url!
  dialogSampleImg.value = true
}
// 预览逻辑
// const handlePictureCardPreviewSix1: UploadProps['onPreview'] = (uploadFile) => {
//   dialogSampleImageUrlChange.value = uploadFile.url!
//   dialogSampleImg.value = true
// }
// 图片上传逻辑
const addNewLoadding = ref(false)
const upLoadMessage = async() => {

  if (!fileListCoverImg.value.length && !fileListSampleImg.value.length) {
    console.error('存在必填项未填写，请重新输入');
    return;
  }
  addNewLoadding.value = true

  const formData = new FormData();
//   上传封面
  fileListCoverImg.value.forEach((file) => {
    if (file.raw instanceof Blob) {
      // 确保 raw 存在并且是 Blob 类型
      formData.append('coverFile', file.raw);
    } else {
      console.warn('File does not have raw data:', file);
    }
  });
// 例图上传
 fileListSampleImg.value.forEach((file) => {
    if (file.raw instanceof Blob) {
      // 确保 raw 存在并且是 Blob 类型
      formData.append('exampleFile', file.raw);
    } else {
      console.warn('File does not have raw data:', file);
    }
  });

  if(AlgorName.value && AlgorDescription.value && ApiLocation.value && valueAdd.value){
    formData.append('algorithmName', AlgorName.value);
    formData.append('description', AlgorDescription.value);
    formData.append('apiAddress', ApiLocation.value);
    formData.append('scenarioID', valueAdd.value);
    formData.append('modelStatus', modelStatusBoo.value == true?"S":"F");
    if(modelStatusBoo.value == false){
      formData.append('cueWord', "");
    }else {
      formData.append('cueWord', tipWord.value);
    }
  }
  try {
    const response = request.post('/algorithm/insertAlgorithm', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }).then(res=>{
       if(res.data.status == "fail"){
        ElMessage.error(`添加算法失败，请检查网络后重试`)
       }else {
        ElMessage({
        message: '添加算法成功',
        type: 'success',
  })
      value.value = ''
      addNewLoadding.value = false
      dialogVisibleAdd.value = false // 关闭弹窗
          //清空数据
      AlgorName.value = '',
      AlgorDescription.value = '',
      ApiLocation.value = '',
      valueAdd.value = '',
      fileListSampleImg.value = [],
      fileListCoverImg.value = [],
      getAllAlgorithm()
       }
    });
  } catch (error) {
    console.error('Upload failed:', error);
  }
}


const handleInputBlur = (row:any) => {
  const formData = new FormData()
  formData.append("id",row.id);
  formData.append("cueWord",row.cueWord)


  request.post('/algorithm/updateCueWord',formData).then((res:any)=> {
    if(res.data.sataus == 'success'){
        // 修改成功调用回调函数
        getAllAlgorithm()
    }
  })

};

// 修改算法演示上传
const changeAlgorithmFlag = ref(false)
const upLoadMessage1 = async() => {  
  if (!fileListCoverImgChange.value.length && !fileListSampleImgChange.value.length) {
    console.error('存在必填项未填写，请重新输入');
    return;
  }

  changeAlgorithmFlag.value = true

  const formData = new FormData();
//   上传封面
  fileListCoverImgChange.value.forEach((file) => {
    if (file.raw instanceof Blob) {
      
      formData.append('coverFile', file.raw);
      formData.append('oldCoverFile', JSON.stringify([]));
    } else if (file.url) {
      formData.append('coverFile',  JSON.stringify([]));
      formData.append('oldCoverFile', file.url);
    } else {
      console.warn('File is neither new nor old:', file);
    }
  });
// 例图上传
 fileListSampleImgChange.value.forEach((file) => {
  if (file.raw instanceof Blob) {
    
      formData.append('exampleFile', file.raw);
      formData.append('oldExampleFile', JSON.stringify([]));

    } else if (file.url) {
     
      formData.append('exampleFile', JSON.stringify([]));
      formData.append('oldExampleFile', file.url);

    } else {
      console.warn('File is neither new nor old:', file);
    }
  });

  if(AlgorNameChange.value && AlgorDescriptionChange.value && ApiLocationChange.value && valueChange.value){
    formData.append('algorithmName', AlgorNameChange.value);
    formData.append('description', AlgorDescriptionChange.value);
    formData.append('apiAddress', ApiLocationChange.value);
    formData.append('scenarioID', valueChange.value);
    formData.append('id', selectedId.value);
    formData.append('primaryAlgorithmName', primaryAlgorithmName.value);
    formData.append('status', selectedStatus.value);
    formData.append('orderNumber', newOrderNumber.value);
    formData.append('modelStatus', modelStatusBoo.value == true?"S":"F");
    if(modelStatusBoo.value == false){
      formData.append('cueWord', "");
    }else {
      formData.append('cueWord', tipWord.value); 
    }
  }
  try {
    const response = request.post('/algorithm/updateAlgorithm', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }).then(res=>{
       if(res.data.status == "fail"){
        ElMessage.error('修改算法详情失败，请检查网络后重试')
       }else {
        changeAlgorithmFlag.value = false
        dialogVisibleChange.value = false; // 关闭弹窗
        ElMessage({
        message: '修改算法成功',
        type: 'success',
  })
      getAllAlgorithm()
      request.post("/algorithm/getAlgorithmByAlgorithmScenarioID", {
        id: value.value,
      }).then((res) => {
        // 更新相关数据
        algorithmByAlgorithmScenarioID.value = res.data;  
      })
       }
    });
  } catch (error) {
    console.error('Upload failed:', error);
  }
}

// 修改算法演示上传
const loading = ref(false)
const upLoadMessage2 = async () => {
  loading.value = true
  if (!dispositionFileList.value.length && !badImageFileOne.value.length && !badImageFileTwo.value.length && !badImageOneDescription.value &&  !badImageTwoDescription.value) {
    ElMessage.error("配置图片失败，请上传图片");
    loading.value = false
    return;
  }

  const formData = new FormData();
  const newFiles: File[] = []; // 明确指定新文件的类型为 File[]
  const oldFileUrls: string[] = []; // 明确指定旧文件 URL 的类型为 string[]
  const newbadFilesOne: File[] = []; // 不好图片1明确指定新文件的类型为 File[]
  const oldbadFileUrlsOne: string[] = []; // 不好图片1明确指定旧文件 URL 的类型为 string[]
  const newbadFilesTwo: File[] = []; // 不好图片2明确指定新文件的类型为 File[]
  const oldbadFileUrlsTwo: string[] = []; // 不好图片2明确指定旧文件 URL 的类型为 string[]

  //上面的6张图片的示例
  // 遍历文件列表，分类处理
  dispositionFileList.value.forEach((file) => {
    if (file.raw instanceof Blob) {
      // 如果是新文件，添加到 newFiles
      newFiles.push(file.raw);
    } else if (file.url) {
      // 如果是旧文件，添加到 oldFileUrls
      oldFileUrls.push(file.url);
    } else {
      console.warn('File is neither new nor old:', file);
    }
  });

  // 将新文件添加到 FormData
  newFiles.forEach((newFile) => {
    formData.append('images', newFile);
  });
  if(newFiles.length === 0) {
    formData.append('images', JSON.stringify([]));
  }

    // 将旧文件 URL 数组添加到 FormData
    formData.append('oldImages', JSON.stringify(oldFileUrls));



    // 效果较差图片1
    // 遍历文件列表，分类处理
    badImageFileOne.value.forEach((file) => {
    if (file.raw instanceof Blob) {
      // 如果是新文件，添加到 newFiles
      newbadFilesOne.push(file.raw);
    } else if (file.url) {
      // 如果是旧文件，添加到 oldFileUrls
      oldbadFileUrlsOne.push(file.url);
    } else {
      console.warn('File is neither new nor old:', file);
    }
  });

  // 将新文件添加到 FormData
  newbadFilesOne.forEach((newbadFilesOne) => {
    formData.append('badImageOne', newbadFilesOne);
  });
  if(newbadFilesOne.length === 0) {
    formData.append('badImageOne', JSON.stringify([]));
  }
  // 将旧文件 URL 数组添加到 FormData
  formData.append('oldBadImageOne', JSON.stringify(oldbadFileUrlsOne));

 // 效果较差图片2
    // 遍历文件列表，分类处理
    badImageFileTwo.value.forEach((file) => {
    if (file.raw instanceof Blob) {
      // 如果是新文件，添加到 newFiles
      newbadFilesTwo.push(file.raw);
    } else if (file.url) {
      // 如果是旧文件，添加到 oldFileUrls
      oldbadFileUrlsTwo.push(file.url);
    } else {
      console.warn('File is neither new nor old:', file);
    }
  });

  // 将新文件添加到 FormData
  newbadFilesTwo.forEach((newbadFilesTwo) => {
    formData.append('badImageTwo', newbadFilesTwo);
  });
  if(newbadFilesTwo.length === 0) {
    formData.append('badImageTwo', JSON.stringify([]));
  }
  // 将旧文件 URL 数组添加到 FormData
  formData.append('oldBadImageTwo', JSON.stringify(oldbadFileUrlsTwo));



  // 添加其他必要的数据
  formData.append('descriptionOne', badImageOneDescription.value);
  formData.append('descriptionTwo', badImageTwoDescription.value);
  formData.append('id', selectedId.value);

  try {
    const response = await request.post('/algorithm/configureImage', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    if (response.data.status === "fail") {
      ElMessage.error("配置图片失败，请重新配置");
    } else {
      ElMessage({
        message: '配置成功',
        type: 'success',
      });
      getAllAlgorithm(); // 刷新数据
     loading.value = false

    }
    ConfigureImageDialogVisible.value = false; // 关闭弹窗
    getAllAlgorithm(); // 刷新数据
  } catch (error) {
    console.error('Upload failed:', error);
    loading.value = false
  }
};




// 获取全部的算法并上传到 store
const showAlgorithm = ref()
const notShowAlgorithm = ref()

const AllAlgorithm = ref([])
const getAllAlgorithm = async () => {
  try {
    const res = await request.get('/algorithm/getAllAlgorithm');
    AllAlgorithm.value = res.data
    showAlgorithm.value = res.data.show
    notShowAlgorithm.value = res.data.notShow
  } catch (error) {
    console.error('Failed to fetch algorithms:', error);
  }
};


//修改状态函数
const handleStatusChange = (item:any) => {

  ElMessageBox.confirm(
    `是否下架/上架算法(${item.algorithmName})？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      request.post('/algorithm/updateAlgorithmStatus',{
    id:item.id,        //  id
    status:item.status,// 新的状态值
  }).then((res)=>{
    if(res.data.status == "fail"){
        ElMessage.error(`修改状态失败，请检查网络后重试`)
        getAllAlgorithm()
       }else {
        ElMessage({
        message: '修改成功',
        type: 'success',
  })
      getAllAlgorithm()
      request.post("/algorithm/getAlgorithmByAlgorithmScenarioID", {
        id: value.value,
      }).then((res) => {
        // 更新相关数据
        algorithmByAlgorithmScenarioID.value = res.data;
      })
       }  
  })
    })
    .catch(() => {
      getAllAlgorithm()
    })

  
}
// 删除逻辑
const deleteItem = (item: any) => {
  ElMessageBox.confirm(
    `是否删除算法(${item.algorithmName})？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      request.post('/algorithm/deleteAlgorithm', {
        id: item.id, // 删除的算法 ID
      }).then((res) => {
        if (res.data.status == "fail") {
          ElMessage.error('删除失败，请检查网络后重试');
        } else {
          ElMessage({
            message: '删除成功',
            type: 'success',
          });

          // 根据筛选状态决定调用哪个接口
          if (value.value) {
            
            // 如果处于筛选状态，重新获取筛选后的数据
            request.post("/algorithm/getAlgorithmByAlgorithmScenarioID", {
              id: value.value,
            }).then((res) => {
              algorithmByAlgorithmScenarioID.value = res.data;
              currentPage.value = 1;
            });
          } else {
            // 如果未筛选，重新获取全部数据
            getAllAlgorithm();
          }
        }
      });
    })
    .catch(() => {
      // 用户取消删除操作
    });
};


const formattedOptions = computed(() =>
    algorStore.algorithmScenario?.map((item: any) => ({
    key: item.id,
    label: item.scenarioName,
    value: item.id,
  }))
);

const formattedOptionsForFilter = computed(() =>[
...algorStore.algorithmScenario?.map((item: any) => ({
    key: item.id,
    label: item.scenarioName,
    value: item.id,
  })),
  { key: "unknown", label: "未知场景", value: -1 },
]);



// 筛选数据，根据选中的场景名称过滤
const tableData = computed(() => {
  if (!value.value) {
    // 返回未筛选的数据
    const newShowAlgorithm = showAlgorithm.value?.map((item: any) => ({
      modelStatus:item.algorithm.modelStatus,
      cueWord:item.algorithm.cueWord,
      id: item.algorithm.id,
      orderNumber: item.algorithm.orderNumber,
      algorithmName: item.algorithm.algorithmName,
      scenarioID: item.algorithm.scenarioID,
      scenarioName:
        formattedOptions.value.find(
          (option: any) => option.value === item.algorithm.scenarioID
        )?.label || "未知场景",
      coverUrl: item.algorithm.coverUrl,
      exampleUrl: item.algorithm.exampleUrl,
      description: item.algorithm.description,
      apiAddress: item.algorithm.apiAddress,
      status: item.algorithm.status,
      imagesArray: item.images.length === 0 ? "配置" : item.images.length,
      images: item.images,
    })) || [];

    const newNotShowAlgorithm = notShowAlgorithm.value?.map((item: any) => ({
      modelStatus:item.algorithm.modelStatus,
      cueWord:item.algorithm.cueWord,
      id: item.algorithm.id,
      orderNumber: item.algorithm.orderNumber,
      algorithmName: item.algorithm.algorithmName,
      scenarioID: item.algorithm.scenarioID,
      scenarioName:
        formattedOptions.value.find(
          (option: any) => option.value === item.algorithm.scenarioID
        )?.label || "未知场景",
      coverUrl: item.algorithm.coverUrl,
      exampleUrl: item.algorithm.exampleUrl,
      description: item.algorithm.description,
      apiAddress: item.algorithm.apiAddress,
      status: item.algorithm.status,
      imagesArray: item.images.length === 0 ? "配置" : item.images.length,
      images: item.images,
    })) || [];

    return [...newShowAlgorithm, ...newNotShowAlgorithm];
  } else {
    // 返回根据场景筛选的数据
    if (algorithmByAlgorithmScenarioID.value) {
      const show = algorithmByAlgorithmScenarioID.value.show?.map((item: any) => ({
        modelStatus:item.algorithm.modelStatus,
        cueWord:item.algorithm.cueWord,
        id: item.algorithm.id,
        orderNumber: item.algorithm.orderNumber,
        algorithmName: item.algorithm.algorithmName,
        scenarioID: item.algorithm.scenarioID,
        scenarioName:
          formattedOptions.value.find(
            (option: any) => option.value === item.algorithm.scenarioID
          )?.label || "未知场景",
        coverUrl: item.algorithm.coverUrl,
        exampleUrl: item.algorithm.exampleUrl,
        description: item.algorithm.description,
        apiAddress: item.algorithm.apiAddress,
        status: item.algorithm.status,
        imagesArray: item.images.length === 0 ? "配置" : item.images.length,
        images: item.images,
      })) || [];

      const notShow = algorithmByAlgorithmScenarioID.value.notShow?.map((item: any) => ({
        modelStatus:item.algorithm.modelStatus,
        cueWord:item.algorithm.cueWord,
        id: item.algorithm.id,
        orderNumber: item.algorithm.orderNumber,
        algorithmName: item.algorithm.algorithmName,
        scenarioID: item.algorithm.scenarioID,
        scenarioName:
          formattedOptions.value.find(
            (option: any) => option.value === item.algorithm.scenarioID
          )?.label || "未知场景",
        coverUrl: item.algorithm.coverUrl,
        exampleUrl: item.algorithm.exampleUrl,
        description: item.algorithm.description,
        apiAddress: item.algorithm.apiAddress,
        status: item.algorithm.status,
        imagesArray: item.images.length === 0 ? "配置" : item.images.length,
        images: item.images,
      })) || [];

      return [...show, ...notShow];
    }
  }
});


const tableDataPaging = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value?.slice(start, end);
});

const totalItems = computed(() => tableData.value?.length);

// 上移下移，沉底，置顶操作
  // 置顶操作
  const  moveToTop =(item:any)=> {

    ElMessageBox.confirm(

`是否将算法(${item.algorithmName})置顶？`,
'警告',
{
  confirmButtonText: '确认',
  cancelButtonText: '取消',
  type: 'warning',
}
)
.then(() => {
  request.post('/algorithm/algorithmMoveToTop',{
    id:item.id,
    scenarioID:item.scenarioID,
  }).then((res=>{
    if(res.data.status == 'success'){
      getAllAlgorithm()
      request.post("/algorithm/getAlgorithmByAlgorithmScenarioID", {
        id: value.value,
      }).then((res) => {
        // 更新相关数据
        algorithmByAlgorithmScenarioID.value = res.data;
      })
    }
  }))
})
.catch(() => {
})
  }

  // 沉底操作
 const moveToBottom = (item:any) => {

  ElMessageBox.confirm(

`是讲算法(${item.algorithmName})沉底？`,
'警告',
{
  confirmButtonText: '确认',
  cancelButtonText: '取消',
  type: 'warning',
}
)
.then(() => {
  request.post('/algorithm/algorithmMoveToBottom',{
    id:item.id,
    scenarioID:item.scenarioID,
  }).then((res=>{
    if(res.data.status == 'success'){
      request.post("/algorithm/getAlgorithmByAlgorithmScenarioID", {
        id: value.value,
      }).then((res) => {
        // 更新相关数据
        algorithmByAlgorithmScenarioID.value = res.data;
      })
    }
  }))
})
.catch(() => {
})
  }

  // 上移操作
 const  moveUp = (item:any) => {
  ElMessageBox.confirm(

`是否将算法(${item.algorithmName})上移一位？`,
'警告',
{
  confirmButtonText: '确认',
  cancelButtonText: '取消',
  type: 'warning',
}
)
.then(() => {
  request.post('/algorithm/algorithmMoveUp',{
    id:item.id,
    scenarioID:item.scenarioID,
  }).then((res=>{
    if(res.data.status == 'success'){
      request.post("/algorithm/getAlgorithmByAlgorithmScenarioID", {
        id: value.value,
      }).then((res) => {
        // 更新相关数据
        algorithmByAlgorithmScenarioID.value = res.data;
      })
    }
  }))
})
.catch(() => {
})
  }

  // 下移操作
 const moveDown = (item:any) => {
  ElMessageBox.confirm(

`是否将算法(${item.algorithmName})下移一位？`,
'警告',
{
  confirmButtonText: '确认',
  cancelButtonText: '取消',
  type: 'warning',
}
)
.then(() => {
  request.post('/algorithm/algorithmMoveDown',{
    id:item.id,
    scenarioID:item.scenarioID,
  }).then((res=>{
    if(res.data.status == 'success'){
      request.post("/algorithm/getAlgorithmByAlgorithmScenarioID", {
        id: value.value,
      }).then((res) => {
        // 更新相关数据
        algorithmByAlgorithmScenarioID.value = res.data;
      })
    }
  }))
})
.catch(() => {
})
  }

  // 获取全部算法场景
  const showAlgorithmScenario = ref()
  const notShowAlgorithmScenario = ref()
  const AllAlgorithmScenario = ref()
  const getAllAlgorithmScenario = async () => {
  try {
    const res = await request.get('/algorithm/getAllAlgorithmScenario');
    showAlgorithmScenario.value = res.data.show || []
    notShowAlgorithmScenario.value = res.data.notShow || []
    AllAlgorithmScenario.value = [...showAlgorithmScenario.value,...notShowAlgorithmScenario.value]
    algorStore.setAlgorData(AllAlgorithmScenario.value);
  } catch (error) {
    console.error('Failed to fetch algorithms:', error);
  }
};

  onMounted(()=>{
    getAllAlgorithmScenario()
    getAllAlgorithm()
  })
  watch(
  () => value.value,
  (newValue) => {
    currentPage.value = 1;
      request.post("/algorithm/getAlgorithmByAlgorithmScenarioID", {
        id: newValue,
      }).then((res) => {
        // 更新相关数据
        algorithmByAlgorithmScenarioID.value = res.data;
        currentPage.value = 1;
          // tableData.value = res.data;
      });
    }
);


</script>

<style  scoped>
.container {
    width: 100%;
    height: 100%;
}
.header {
    width: 100%;
    height: 14%;
}
.main {
    width: 100%;
    height: 76%;
}
.el-pagination {
  background-color: transparent !important; /* 移除背景颜色 */
  box-shadow: none !important;             /* 去掉可能的阴影 */
}
</style>